import { defineStore } from "pinia";
import { useStorage } from "@vueuse/core";
import {
  LoginParamType,
  UserContextResultType,
  login,
  getUseContext,
  getAppsList,
} from "@/api/auth/index";
import { listToTree, filterTree } from "@/utils/tree";
import router from "@/router";

export const useUserStore = defineStore("user", () => {
  const user = reactive<UserContextResultType>({
    name: "", // 姓名
    userName: "", // 账号
    userAppObj: JSON.parse(localStorage.getItem("appObj") as any) || {}, // 当前小程序对象
    changePassword: false, // 是否重置密码
    menus: <Array<any>>[], // 权限菜单
    permissions: <Array<any>>[], // 按钮权限
    isOperate: false, // 是否为运营人员
    userAppid: localStorage.getItem("userAppid") || "", // 用户绑定的appid
    userApps: JSON.parse(localStorage.getItem("userApps") as string) || [], // 用户小程序
    operaLastPage: (localStorage.getItem("operaLastPage") as string) || "", // 最近一次页面路由 - 剧目平台
    yyLastPage: (localStorage.getItem("yyLastPage") as string) || "", // 最近一次页面路由 - 运营平台
  });
  const token = useStorage<string | null>("token", null);

  async function getToken(params: LoginParamType) {
    const res = (await login(params)) as Record<string, any>;
    token.value = res.data?.token;
    user.changePassword = res.data?.changePassword;
    await getUser();

    // 判断是否为运营平台 是则跳转
    if (user.isOperate) {
      const page = user.yyLastPage.split("~");
      const url = page[0] === user.userName ? page[1] : `/`;
      window.location.href = url;
    } else {
      getUserApps();
    }
  }

  async function clearToken() {
    token.value = null;
  }

  async function getUser() {
    const res = (await getUseContext()) as Record<string, any>;
    user.userName = res.data?.user.userName; // 登录没有id，暂时使用账号名记录用户
    user.name = res.data?.user?.name;
    user.permissions = res.data?.permissions; // 按钮权限

    user.menus =
      res?.success && (res?.data?.menus?.length as number) > 0
        ? handleMenu(res.data?.menus)
        : [];
    // console.log("按钮权限", user.permissions);
    // console.log("菜单权限", user.menus);
    let page;
    if (user.isOperate) {
      page = user.yyLastPage.split("~");
    } else {
      if (!user.userApps.length) return;
      page = user.operaLastPage.split("~");
    }
    const url = page[0] === user.userName ? page[1] : `/`;
    router.push(url);
  }

  // 获取用户apps
  async function getUserApps() {
    getAppsList().then((res: any) => {
      // 判断是否有分配小程序给用户
      if (!res?.length) {
        return ElMessage.error(
          "未给该用户分配小程序，会导致某些功能异常，请分配后重新登录！"
        );
      } else if (res?.length === 1) {
        user.userAppid = res[0]?.id;
        localStorage.setItem("userAppid", user.userAppid);
      } else if (res?.length > 1) {
        // 当用户存在多个小程序时，取缓存中最近一次登录的那个小程序appid登录,
        const userNameAppid = localStorage.getItem(
          `@${user.userName}`
        ) as string;
        const hasAppid = res.some(
          (x: Record<string, any>) => x?.id == userNameAppid
        );
        // 判断是否返回的数据中存在appid，存在即直接存入user.userAppid中
        if (hasAppid) {
          switchAppid(userNameAppid);
        }
      }

      const page = user.operaLastPage.split("~");
      const url = page[0] === user.userName ? page[1] : `/`;
      // router.push(url);
      window.location.href = url;

      user.userApps = res;
      localStorage.setItem("userApps", JSON.stringify(user.userApps));

      if (user.userAppid) {
        user.userAppObj = res.find((x: any) => x.id == user.userAppid);
        localStorage.setItem("appObj", JSON.stringify(user.userAppObj));
      }

      // 如果用户重置密码了，跳转至登录页
      if (user.changePassword) {
        nextTick(() => {
          setTimeout(() => {
            window.location.href = `/password/index`;
          });
        });
      }
    });
  }

  // actions
  function switchAppid(appid: string) {
    user.userAppid = appid;
    localStorage.setItem("userAppid", appid);
  }

  function setAppObj(val: any) {
    user.userAppObj = val;
    localStorage.setItem("appObj", JSON.stringify(val));
  }

  // 菜单数据处理
  function handleMenu(data: any) {
    const menus = [] as any;
    data?.forEach((menu: Record<string, any>) => {
      menus.push({
        id: menu.id,
        parentId: menu.parentId,
        name: menu.name ? menu.name : menu.id + "",
        path: menu.path ? menu.path : menu.id + "",
        redirect: menu.redirect,
        component: menu.viewPath ? menu.viewPath : "Layout",
        meta: {
          title: menu.label as string,
          icon: menu.icon,
          isAffix: menu.isAffix,
          hidden: menu.hidden,
          isIframe: menu.isIframe,
          isKeepAlive: menu.isKeepAlive,
          isLink: menu.link,
          status: 1,
          remark: null,
          order: menu.sort,
          isDir: !menu.viewPath,
        },
      });
    });

    // console.log("listToTree(menus)---", listToTree(menus));
    // 判断返回的菜单是否为运营中心（path == '/operate'）,是则 user.isOperate 的值为true 否则为false
    if (
      listToTree(menus).some((x: Record<string, any>) => x.path === "/agent")
    ) {
      user.isOperate = false;
    } else {
      user.isOperate = true;
    }
    const menuTree = listToTree(menus).find((x: Record<string, any>) => {
      // 分销商ID：472937267826757 (/agent)    运营中心：484470063788101 (/operate)
      if (x.path === "/agent" || x.path === "/operate") {
        return x;
      }
    })?.children;
    // console.log("menuTree---", menuTree);
    return menuTree;
  }

  return {
    user,
    token,
    getToken,
    clearToken,
    getUser,
    switchAppid,
    setAppObj,
  };
});
